package shanghaielectric_lib.Utils;

/**
 * Created by Administrator on 2017/8/20 0020.
 */

public class MyArrayUtils {
    public static char[] reverseCharsArray(char[] chars){
        int length=chars.length;
        char [] result=new char[length];
        for (int i = 0; i <length ; i++) {
            result[i]=chars[length-i-1];
        }
        return result;
    }

    public static String[] reverseStringArray(String[] str){
        int length=str.length;
        String [] result=new String[length];
        for (int i = 0; i <length ; i++) {
            result[i]=str[length-i-1];
        }
        return result;
    }
    public static byte[] intToByteArray_2(int i) {

        byte[] result = new byte[2];

        result[0] = (byte)((i >> 8) & 0xFF);
        result[1] = (byte)(i & 0xFF);
        return result;
    }

    /**
     * 把16进制字符串转换成字节数组
     * @param hexString
     * @return byte[]
     */
    public static byte[] hexStringToByte(String hex) {
        int len = (hex.length() / 2);
        byte[] result = new byte[len];
        char[] achar = hex.toCharArray();
        for (int i = 0; i < len; i++) {
            int pos = i * 2;
            result[i] = (byte) (toByte(achar[pos]) << 4 | toByte(achar[pos + 1]));
        }
        return result;
    }

    private static int toByte(char c) {
        byte b = (byte) "0123456789ABCDEF".indexOf(c);
        return b;
    }

//    数组转换成十六进制字符串方法1：

//    /**
//     * 数组转换成十六进制字符串
//     * @param byte[]
//     * @return HexString
//     */
//    public static final String bytesToHexString(byte[] bArray) {
//        StringBuffer sb = new StringBuffer(bArray.length);
//        String sTemp;
//        for (int i = 0; i < bArray.length; i++) {
//            sTemp = Integer.toHexString(0xFF & bArray[i]);
//            if (sTemp.length() < 2)
//                sb.append(0);
//            sb.append(sTemp.toUpperCase());
//        }
//        return sb.toString();
//    }
    /**
     * 效率比较高,比上面的高
     * */
    public static String byteArrayToHexStr(byte[] byteArray) {
        if (byteArray == null){
            return null;
        }
        char[] hexArray = "0123456789ABCDEF".toCharArray();
        char[] hexChars = new char[byteArray.length * 2];
        for (int j = 0; j < byteArray.length; j++) {
            int v = byteArray[j] & 0xFF;
            hexChars[j * 2] = hexArray[v >>> 4];
            hexChars[j * 2 + 1] = hexArray[v & 0x0F];
        }
        return new String(hexChars);
    }
}
